package dto

import (
	"fmt"
	"net/http"
)

var (
	Success                     = NewError(0, "请求成功")
	ServerError                 = NewError(20001, "服务器错误")
	InvalidParams               = NewError(20002, "参数错误")
	NotFound                    = NewError(20003, "找不到")
	TooManyRequests             = NewError(20004, "请求过于频繁")
	UnauthorizedAuthNotExist    = NewError(20005, "鉴权失败，找不到对应权限")
	UnauthorizedTokenError      = NewError(20006, "鉴权失败，Token错误")
	UnauthorizedTokenTimeout    = NewError(20007, "鉴权失败，Token超时")
	UnauthorizedTokenGeneration = NewError(20008, "鉴权失败，Token生成失败")
)

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

var codes = map[int]string{}

func NewError(code int, msg string) *Error {
	if _, ok := codes[code]; ok {
		panic(fmt.Sprintf("错误码 %d 已存在，请换一个", code))
	}
	codes[code] = msg
	return &Error{Code: code, Message: msg}
}

func (e *Error) Error() string {
	return fmt.Sprintf("错误码：%d，错误信息：%s", e.Code, e.Message)
}

func (e *Error) StatusCode() int {
	switch e.Code {
	case Success.Code:
		return http.StatusOK
	case ServerError.Code:
		return http.StatusInternalServerError
	case InvalidParams.Code:
		return http.StatusBadRequest
	case NotFound.Code:
		return http.StatusNotFound
	case TooManyRequests.Code:
		return http.StatusTooManyRequests
	case UnauthorizedAuthNotExist.Code:
		fallthrough
	case UnauthorizedTokenError.Code:
		fallthrough
	case UnauthorizedTokenTimeout.Code:
		fallthrough
	case UnauthorizedTokenGeneration.Code:
		return http.StatusUnauthorized
	}
	return http.StatusInternalServerError
}
